<template>
  <div>
    <div class="supply-mng moudle-item">
      <px-tabs v-model="activeTab" class="equipment-tabs" style="margin-bottom: 10px; background: none" @tab-change="activeTabChange">
        <px-tab-pane v-for="(item, index) in tabPaneList" :key="index" :name="item.name">
          <template #label>
            <p class="pane-bottom">{{ item.label }}</p>
            <p class="pane-line" />
          </template>
        </px-tab-pane>
      </px-tabs>
      <div class="swtich-btn"><px-switch v-model="switchFlag" active-text="实时" inactive-text="保持" /></div>
      <div>
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
          <px-form-item label="" prop="timePeriod" class="time-type-item">
            <px-radio-group v-model="queryParams.timePeriod" @change="handleChange">
              <px-radio-button label="minutes">分钟</px-radio-button>
              <px-radio-button label="hour">小时</px-radio-button>
              <px-radio-button label="day">天</px-radio-button>
              <px-radio-button label="week">周</px-radio-button>
              <px-radio-button label="months">月</px-radio-button>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="日期" style="width: 416px !important" prop="timeRange">
            <px-date-picker
              v-model="queryParams.timeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
              :shortcuts="shortcuts"
            />
          </px-form-item>

          <!-- <px-form-item label="厂区">
            <px-select v-model="queryParams.fabCode" placeholder="请选择" clearable style="width: 240px" filterable>
              <px-option v-for="dict in fabList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
            </px-select>
          </px-form-item> -->
          <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery()">查询</px-button>
          <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
        </px-form>
      </div>
      <div>
        <px-table min-height="120" :data="tableData" border style="width: 100%" :cell-class-name="cellClassName">
          <template #empty>
            <px-empty />
          </template>
          <px-table-column prop="pointName" label="点位" width="100" />
          <px-table-column v-for="(item, i) in submainList" :key="i" :prop="`submain_${i}`" :label="item">
            <template #default="scope">
              {{ scope.row.subList[i].value }}
              <!-- <span v-if="scope.row.subList[i].isOos" class="warning-icon"> <oosIcon /> </span
              ><span v-else-if="scope.row.subList[i].isOoc" class="warning-icon"> <oocIcon /> </span
              ><span v-else-if="scope.row.subList[i].isOow" class="warning-icon"> <oowIcon /> </span>{{ scope.row.subList[i].value
              }}<span
                v-if="scope.row.subList[i].isOos || scope.row.subList[i].isOoc || scope.row.subList[i].isOow"
                class="warning-text"
                :class="{ 'is-oos': scope.row.subList[i].isOos, 'is-ooc': scope.row.subList[i].isOoc, 'is-oow': scope.row.subList[i].isOow }"
                >{{ scope.row.subList[i].isOos ? "[oos]" : scope.row.subList[i].isOow ? "[oow]" : scope.row.subList[i].isOoc ? "[ooc]" : "" }}</span
              > -->
            </template>
          </px-table-column>

          <px-table-column prop="time" label="time" width="120" />
        </px-table>
        <div class="box">
          <!-- <div class="left">
            <div class="box-title">
              <px-select v-model="activeSubmain" placeholder="请选择" style="width: 110px" filterable @change="submainChange">
                <px-option v-for="(item, i) in submainList" :key="i" :label="item" :value="i" /> </px-select
              >&nbsp;指标分析
            </div>
            <div class="box-border" style="padding-top: 8px">
              <div v-if="pointList.length > 0" class="chart-container">
                <div class="chart-wrapper">
                  <px-tabs v-model="alarmType" class="equipment-tabs" @tab-change="alarmTypeChange">
                    <px-tab-pane name="all">
                      <template #label>
                        <p class="pane-bottom">ALARM({{ spcAlarm.totalCount }})</p>
                        <p class="pane-line" />
                      </template>
                    </px-tab-pane>

                    <px-tab-pane name="ooc">
                      <template #label>
                        <p class="pane-bottom">OOC({{ spcAlarm.totalOocCount }})</p>
                        <p class="pane-line" />
                      </template>
                    </px-tab-pane>
                    <px-tab-pane name="oow">
                      <template #label>
                        <p class="pane-bottom">OOW({{ spcAlarm.totalOowCount }})</p>
                        <p class="pane-line" />
                      </template>
                    </px-tab-pane>
                    <px-tab-pane name="oos">
                      <template #label>
                        <p class="pane-bottom">OOS({{ spcAlarm.totalOosCount }})</p>
                        <p class="pane-line" />
                      </template>
                    </px-tab-pane>
                  </px-tabs>
                </div>

                <div class="chartsdom">
                  <chartoption :SpcAnalysis="spcChartsList" :tabvalue="dataPoint" :width="'100%'" :height="'405px'" />
                </div>
              </div>
              <px-empty v-else class="chartsdom" />
            </div>
          </div> -->
          <div class="right">
            <div class="box-title">热力图分析</div>
            <div class="box-border">
              <px-radio-group v-model="hotActiveName" @change="hotActiveChange">
                <px-radio-button v-for="(item, i) in pointConfigList" :key="i" :label="i">{{ item.itemName }}</px-radio-button>
              </px-radio-group>
              <echartsChart ref="chartRef" :boxShadow="false" :options="chartOptions" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div class="moudle-item">
      <div class="prediction-search">
        <px-form ref="queryRef" class="custom-form-ui" :model="queryParamsp" :inline="true" label-width="90px">
          <px-form-item label="">
            <px-select v-model="queryParamsp.fabCode" placeholder="请选择" style="width: 240px" filterable @change="fabChange">
              <px-option v-for="dict in fabList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
            </px-select>
          </px-form-item>
          <px-form-item label="">
            <px-select v-model="queryParamsp.exhaustGas" placeholder="请选择" style="width: 240px" filterable @change="gasChange">
              <px-option v-for="dict in predictionlist" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
            </px-select>
          </px-form-item>
          <px-form-item label="" prop="timePeriod" class="time-type-item">
            <px-radio-group v-model="queryParamsp.timePeriod" @change="handleQueryP">
              <px-radio-button label="minutes">分钟</px-radio-button>
              <px-radio-button label="hour">小时</px-radio-button>
              <px-radio-button label="day">天</px-radio-button>
              <px-radio-button label="week">周</px-radio-button>
              <px-radio-button label="months">月</px-radio-button>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="日期" style="width: 416px !important" prop="timeRange">
            <px-date-picker
              v-model="queryParamsp.timeRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
              :shortcuts="shortcuts"
            />
          </px-form-item>
          <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQueryP()">查询</px-button>
          <px-button style="margin-top: -17px" icon="" @click="resetQueryP">重置</px-button>
        </px-form>
      </div>
      <px-tabs v-model="activeMeasure" class="equipment-tabs" style="margin-bottom: 10px; background: none" @tab-change="activeMeasureChange">
        <px-tab-pane v-for="(item, index) in measureList" :key="index" :name="item.measureName">
          <template #label>
            <p class="pane-bottom">{{ item.measureName }}</p>
            <p class="pane-line" />
          </template>
        </px-tab-pane>
      </px-tabs>
      <div>
        <echartsChart ref="lineRef" :boxShadow="false" :options="lineOptions" />
      </div>
    </div> -->
  </div>
</template>
<script setup lang="ts">
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import { getCurrentInstance, ref, unref, toRefs, reactive, onMounted, onUnmounted, watchEffect, nextTick } from "vue";
import { queryChildByTypeCodeAndItemValue, queryMeasureByCodes, queryTimePredicatedEXHData } from "@/api/machineClass";
import { spcquerySpcAnalysis, spcIndicatorqueryResultCount } from "@/api/spc";
import chartoption from "./components/chartoption.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import dayjs from "dayjs";
import oosIcon from "@/assets/svg/machine/oos_warning.svg?component";
import oocIcon from "@/assets/svg/machine/ooc_warning.svg?component";
import oowIcon from "@/assets/svg/machine/oow_warning.svg?component";
import { PxLoading } from "px-ui";
defineOptions({
  name: "MACHINE_SUPPLY_COOLING"
});

const { proxy }: any = getCurrentInstance();

const data = reactive({
  queryParams: {
    timeRange: [
      proxy.parseTime(new Date().getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
      proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
    ],
    startTime: "",
    endTime: "",
    timePeriod: "hour",
    fabCode: ""
  },
  queryParamsp: {
    timeRange: [dayjs().subtract(4, "hour").format("YYYY-MM-DD HH:mm:ss"), dayjs().format("YYYY-MM-DD HH:mm:ss")],
    startTime: "",
    endTime: "",
    timePeriod: "hour",
    fabCode: "",
    exhaustGas: ""
  },
  tableData: [],
  fabList: [],
  exhaustGasList: [],
  dataPoint: "",
  pointList: [], //33个点位
  pointConfigList: [], //配置的所有点位信息
  spcChartsList: [],
  hotChartList: [],
  spcAlarm: {},
  alarmType: "",
  timerId: null,
  switchFlag: true,
  hotActiveName: 0,
  chartRef: null,
  lineRef: null,
  chartOptions: null,
  lineOptions: null,
  submainList: [],
  activeSubmain: 0,
  predictionlist: [],
  measureList: [],
  spcLineData: [],
  predictionData: []
});

const {
  queryParams,
  queryParamsp,
  tableData,
  fabList,
  exhaustGasList,
  dataPoint,
  pointList,
  pointConfigList,
  spcChartsList,
  hotChartList,
  spcAlarm,
  alarmType,
  timerId,
  switchFlag,
  hotActiveName,
  chartRef,
  lineRef,
  chartOptions,
  lineOptions,
  submainList,
  activeSubmain,
  predictionlist,
  measureList,
  spcLineData,
  predictionData
} = toRefs(data);
const shortcuts = [
  {
    text: "今日",
    value: () => {
      let now = new Date();
      return [dayjs(dayjs(now).format("YYYY-MM-DD") + " 00:00:00"), dayjs(dayjs(now).format("YYYY-MM-DD") + " 23:59:59")];
    }
  },
  {
    text: "最近7天",
    value: () => {
      let now = dayjs();
      let start = now.subtract(7, "day").format("YYYY-MM-DD HH:mm:ss");
      return [start, now.format("YYYY-MM-DD HH:mm:ss")];
    }
  },
  {
    text: "最近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      // const start = new Date();
      // 获取当前月份第一天
      const start = dayjs(new Date(end.getFullYear(), end.getMonth(), 1)).format("YYYY-MM-DD HH:mm:ss");
      return [start, end];
    }
  }
];
const activeTab = ref("SEX");
const activeMeasure = ref("");
const tabPaneList = [
  {
    label: "SEX",
    name: "SEX"
  },
  {
    label: "AEX",
    name: "AEX"
  },
  {
    label: "VEX",
    name: "VEX"
  },
  {
    label: "PGEX",
    name: "PGEX"
  },
  {
    label: "ASX",
    name: "ASX"
  },
  {
    label: "SEX-EPI",
    name: "SEX-EPI"
  },
  {
    label: "PGEX-EPI",
    name: "PGEX-EPI"
  }
];

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}

const handleChange = val => {
  queryParams.value.timePeriod = val;
  handleQuery();
};

const handleQuery = () => {
  console.log("queryParams.value:", queryParams.value);
  if (switchFlag.value) {
    if (queryParams.value.timePeriod === "minutes") {
      queryParams.value.timeRange = [dayjs().subtract(4, "hour").format("YYYY-MM-DD HH:mm:ss"), dayjs().format("YYYY-MM-DD HH:mm:ss")];
    }
    if (queryParams.value.timePeriod === "hour") {
      queryParams.value.timeRange = [
        proxy.parseTime(new Date().getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
        proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
      ];
    }
  }
  querySpcChartList("");
  // let parmas = {
  //   systemCode: queryParams.value.systemCode,
  //   samplingLocationCode: queryParams.value.samplingLocationCode,
  //   testItem: queryParams.value.testItem,
  //   samplingTimeStart: dateRange.value[0],
  //   samplingTimeEnd: dateRange.value[1]
  // };
};
const drawLineChart = (legend, xAxisData, seriesData) => {
  lineOptions.value = {
    title: {
      text: `Exhaust Gas Analysis with Dual Y-Axis for ${activeMeasure.value}`
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: legend,
      top: "middle",
      right: 0,
      orient: "vertical"
    },
    grid: {
      left: "3%",
      right: "10%",
      bottom: "3%",
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: xAxisData
    },
    yAxis: {
      type: "value"
    },
    series: seriesData
  };
  lineRef.value.updateEchartsOption();
};

const alignData = (list, data) => {
  let t = [];
  list.forEach(v => {
    let f = data.filter(item => item.name == v);
    if (f.length) {
      t.push(f[0].value);
    } else {
      t.push(null);
    }
  });
  return t;
};
const handleQueryP = async () => {
  // 查询spc、查询预测
  if (!queryParamsp.value.timeRange[0] || !queryParamsp.value.timeRange[1] || !pointList.value.length || !activeMeasure.value) {
    return;
  }
  let activeMeasuerCode = measureList.value.filter(v => v.measureName == activeMeasure.value)[0].measureCode;
  let aiPointCode = "",
    taskType = "";
  let citem = predictionlist.value.filter(v => v.itemValue == queryParamsp.value.exhaustGas);
  if (citem.length && citem[0].itemDesc) {
    let ccode = JSON.parse(citem[0].itemDesc).filter(v => v.actualPoint == activeMeasuerCode);
    aiPointCode = ccode?.[0]?.AiPoint;
    taskType = ccode?.[0]?.task_type;
  }
  Promise.allSettled([
    spcquerySpcAnalysis({
      pointList: [activeMeasuerCode, ...pointList.value], //所有点位
      timePeriod: queryParamsp.value.timePeriod,
      startTime: queryParamsp.value.timeRange[0],
      endTime: queryParamsp.value.timeRange[1]
    }),
    queryTimePredicatedEXHData({
      taskType,
      startTime: queryParamsp.value.timeRange[0],
      endTime: queryParamsp.value.timeRange[1],
      paramList: [aiPointCode],
      actualParamList: [activeMeasuerCode],
      timePeriod: queryParamsp.value.timePeriod
    })
  ]).then((res: any[]) => {
    let spcDataList = res[0].value;
    let actualData = res[1]?.value?.[1];
    actualData =
      actualData[activeMeasuerCode]?.map(v => {
        return { name: v.dateTimeResult, value: v.value };
      }) || [];
    let aiData = res[1]?.value?.[0];
    aiData =
      aiData[activeMeasuerCode]?.map(v => {
        return { name: v.dateTimeResult, value: v.value };
      }) || [];
    let seriesList = [],
      xAxisData = [];
    let spcDates = spcDataList[0].pointValues.map(v => dayjs(v.time).format("YYYY-MM-DD HH:mm:ss"));
    let dates = [...spcDates, ...aiData?.map(v => v.name), ...actualData?.map(v => v.name)];
    let combinedDates = dates.sort((a, b) => {
      return dayjs(a).isBefore(dayjs(b)) ? -1 : 1;
    });
    xAxisData = [...new Set(combinedDates)]; // 去重
    let legend = [`AI Predicted ${activeMeasure.value}`, `Actual ${activeMeasure.value}`, "SPC Line", ...submainList.value];
    seriesList.push({
      name: legend[0],
      type: "line",
      connectNulls: true,
      // smooth: true,
      showSymbol: false,
      data: alignData(xAxisData, aiData)
    });
    seriesList.push({
      name: legend[1],
      type: "line",
      connectNulls: true,
      // smooth: true,
      showSymbol: false,
      data: alignData(xAxisData, actualData)
    });
    let spcInfo = spcDataList.filter(v => v.point == activeMeasuerCode);
    if (spcInfo && spcInfo.length) {
      let sd = [];
      xAxisData.forEach(v => {
        sd.push(spcInfo[0].lclValue); //lclValue
      });
      seriesList.push({
        name: legend[2],
        type: "line",
        connectNulls: true,
        // smooth: true,
        showSymbol: false,
        data: sd //lclValue
      });
    }
    for (var i = 0; i < pointConfigList.value.length; i++) {
      for (var j = 0; j < submainList.value.length; j++) {
        let spckey = Object.keys(pointConfigList.value[i].pointList)[j];
        let point = pointConfigList.value[i].pointList[spckey];
        let spcData = spcDataList.filter(v => v.point == point);
        let d = spcData[0].pointValues.map(v => {
          return { value: v.value, name: dayjs(v.time).format("YYYY-MM-DD HH:mm:ss") };
        });
        seriesList.push({
          name: submainList.value[j],
          type: "line",
          connectNulls: true,
          // smooth: true,
          showSymbol: false,
          lineStyle: {
            // color: '#333', // 线条颜色
            type: "dashed" // 线条类型设置为虚线
          },
          data: alignData(xAxisData, d)
        });
      }
    }

    drawLineChart(legend, xAxisData, seriesList);
  });
};
const fabChange = () => {
  // TODO
};
const gasChange = () => {
  getMeasureList();
};
const resetQuery = () => {
  const start = proxy.parseTime(new Date().getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
  const end = proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}");
  queryParams.value = {
    timeRange: [start, end],
    startTime: start,
    endTime: end,
    timePeriod: "hour",
    fabCode: ""
  };
};
const resetQueryP = () => {
  queryParamsp.value = {
    timeRange: "",
    startTime: "",
    endTime: "",
    timePeriod: "hour",
    fabCode: "",
    exhaustGas: ""
  };
};
const getMeasureList = async () => {
  let item = predictionlist.value.filter(v => v.itemValue == queryParamsp.value.exhaustGas);
  if (item.length && item[0].itemDesc) {
    let codes = JSON.parse(item[0].itemDesc).map(v => v.actualPoint);
    let res: any = await queryMeasureByCodes(codes);
    measureList.value = res;
    activeMeasure.value = res?.[0].measureName;
  } else {
    measureList.value = [];
  }
  handleQueryP();
};
const getPerdictionDict = async () => {
  // 默认查一期的
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "MIC_EXHAUST_GROUP",
    typeCode: "MCTS"
  });
  predictionlist.value = data;
  queryParamsp.value.exhaustGas = data?.[0].itemValue;
  getMeasureList();
};

const getPointList = async type => {
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: type,
    typeCode: "MCTS"
  });
  let list = [],
    tList = [],
    tmpSubmainList = [];
  data.forEach(item => {
    let pointO = JSON.parse(item.itemDesc);
    tList.push({
      itemName: item.itemName,
      pointList: pointO
    });
    const values = Object.values(pointO);
    tmpSubmainList = tmpSubmainList.concat(Object.keys(pointO));
    const nonEmptyValues = values.filter(value => value !== null && value !== undefined && value !== "");
    list = list.concat(nonEmptyValues);
  });
  pointList.value = list;
  pointConfigList.value = tList;
  submainList.value = tmpSubmainList;
  await nextTick();
  handleQuery();
  handleQueryP();
};

const getFabList = async () => {
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "",
    typeCode: "factoryArea"
  });
  fabList.value = data;
  queryParams.value.fabCode = data?.[0]?.itemValue;
  queryParamsp.value.fabCode = data?.[0]?.itemValue;
};
const resetPageData = () => {
  tableData.value = [];
  hotChartList.value = [];
  spcChartsList.value = [];
};
const querySpcChartList = async (type: "") => {
  let serveLoading = null;
  try {
    if (!queryParams.value.timeRange[0] || !queryParams.value.timeRange[1] || !pointList.value.length) {
      resetPageData();
      return;
    }
    serveLoading = PxLoading.service({
      lock: true,
      text: "Loading",
      background: "rgba(0, 0, 0, 0.5)"
    });
    let res = await spcquerySpcAnalysis({
      pointList: [...pointList.value], //所有点位
      alarmType: type,
      timePeriod: queryParams.value.timePeriod,
      startTime: queryParams.value.timeRange[0],
      endTime: queryParams.value.timeRange[1]
    });
    if (serveLoading) {
      serveLoading.close();
    }
    // spcChartsList.value = res
    if (!type) {
      hotChartList.value = res;
      getSpcChartData("");
      getHotChartsOptions();
      // 组装 table 数据
      tableData.value = [];
      for (var i = 0; i < pointConfigList.value.length; i++) {
        let pointName = pointConfigList.value[i].itemName;
        let subList = [],
          time = "";
        for (var j = 0; j < submainList.value.length; j++) {
          let spckey = Object.keys(pointConfigList.value[i].pointList)[j];
          let point = pointConfigList.value[i].pointList[spckey];
          let spcData = res.filter(v => v.point == point);
          let value = "",
            time = "";
          let isOos = false,
            isOow = false,
            isOoc = false;
          if (spcData.length) {
            if (spcData[0]?.pointValues?.length) {
              value = spcData[0].pointValues[spcData[0].pointValues.length - 1].value;
              time = spcData[0].pointValues[spcData[0].pointValues.length - 1].time
                ? dayjs(spcData[0].pointValues[spcData[0].pointValues.length - 1].time).format("YYYY-MM-DD HH:mm:ss")
                : "";
              isOos = value > spcData[0].uslValue || value < spcData[0].lslValue ? true : false;
              isOow = value > spcData[0].uwlValue || value < spcData[0].lwlValue ? true : false;
              isOoc = value > spcData[0].uclValue || value < spcData[0].lclValue ? true : false;
            }
          }
          subList.push({
            value,
            isOos,
            isOow,
            isOoc,
            time
          });
        }
        let t = subList.filter(v => v.time != "");
        tableData.value.push({
          pointName,
          subList,
          time: t.length ? t[0].time : ""
        });
      }
    } else {
      //警告的数据 影响 spc图表展示 TODO
      getSpcChartData(type);
    }
  } catch (error) {
    console.log(error);
    if (serveLoading) {
      serveLoading.close();
    }
  }
};
const alarmTypeChange = () => {
  querySpcChartList(alarmType.value);
};
const querySpcAnalysisResultList = async points => {
  try {
    if (points.length) {
      let res = await spcIndicatorqueryResultCount({
        pointList: [...points],
        classCode: "MACHINE",
        // jobIdList: [...checkList1.value, ...checkList2.value],
        alarmType: "",
        startTime: queryParams.value.timeRange[0],
        endTime: queryParams.value.timeRange[1]
      });
      spcAlarm.value.totalCount = res?.totalCount || 0;
      spcAlarm.value.totalOocCount = res?.totalOocCount || 0;
      spcAlarm.value.totalOowCount = res?.totalOowCount || 0;
      spcAlarm.value.totalOosCount = res?.totalOosCount || 0;
    } else {
      spcAlarm.value.totalCount = "";
      spcAlarm.value.totalOocCount = "";
      spcAlarm.value.totalOowCount = "";
      spcAlarm.value.totalOosCount = "";
    }
  } catch (error) {
    console.log(error);
  }
};
const cellClassName = ({ row, column, rowIndex, columnIndex }) => {
  // if (column) {
  //   if (column.property.indexOf("submain") != -1) {
  //     let i = column.property.split("_")[1];
  //     if (row.subList[i].isOos) {
  //       return "oos";
  //     }
  //     if (row.subList[i].isOoc) {
  //       return "ooc";
  //     }
  //     if (row.subList[i].isOow) {
  //       return "oow";
  //     }
  //   }
  // }
  return "";
};
const startClock = () => {
  clearClock();
  timerId.value = setInterval(() => {
    //调用接口
    // 设置查询条件
    // if (queryParams.value.timeRange && queryParams.value.timeRange[0]) {
    //   queryParams.value.timePeriod = "minutes";
    //   queryParams.value.timeRange[1] = dayjs().format("YYYY-MM-DD HH:mm:ss");
    //   if (dayjs(queryParams.value.timeRange[0]).isBefore(dayjs().subtract(4, "hour"))) {
    //     queryParams.value.timeRange[0] = dayjs().subtract(4, "hour").format("YYYY-MM-DD HH:mm:ss");
    //   }
    // }
    handleQuery();
  }, 8000);
};
const clearClock = () => {
  clearInterval(timerId.value);
};
watchEffect(() => {
  // 判断实时开关是否打开
  if (switchFlag.value) {
    startClock();
  } else {
    clearClock();
  }
});
const hotActiveChange = () => {
  getHotChartsOptions();
};
const getSpcChartData = type => {
  //获取spcpoint
  let chartList = [];
  dataPoint.value = "";
  let pointList = [];
  for (var i = 0; i < pointConfigList.value.length; i++) {
    // 获取第一个属性的value
    let spckey = Object.keys(pointConfigList.value[i].pointList)[activeSubmain.value];
    let point = pointConfigList.value[i].pointList[spckey];
    let spcData = hotChartList.value.filter(v => v.point == point);
    if (spcData.length) {
      if (!dataPoint.value) {
        dataPoint.value = point;
      }
      pointList.push(spcData[0].point);
      chartList.push(spcData[0]);
    }
  }
  spcChartsList.value = chartList;
  if (!type) {
    querySpcAnalysisResultList(pointList);
  }
};
//重新获取chart数据 TODO
const submainChange = () => {
  getSpcChartData("");
};

const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};
const getHotMapData = (pointValues, timeList) => {
  let data = [];
  for (let i = 0; i < timeList.length; i++) {
    for (let j = 0; j < submainList.value.length; j++) {
      data.push([i, j, valueIsEmpty(pointValues[j][i]?.value) ? "" : pointValues[j][i]?.value]);
    }
  }
  return data;
};
const getHotChartsOptions = () => {
  let pointValues = [];
  let timeList = [];
  let min = "",
    max = "";
  let seriesName = pointConfigList.value[hotActiveName.value].itemName;
  for (var i = 0; i < submainList.value.length; i++) {
    //11个
    let spckey = Object.keys(pointConfigList.value[hotActiveName.value].pointList)[i];
    let point = pointConfigList.value[hotActiveName.value].pointList[spckey];
    let spcData = hotChartList.value.filter(v => v.point == point);
    let value = [];
    if (spcData.length) {
      if (spcData[0]?.pointValues?.length) {
        value = spcData[0].pointValues;
        if (valueIsEmpty(min)) {
          let minValue = value.reduce((min, obj) => {
            return obj.value < min ? obj.value : min;
          }, Infinity);
          min = Math.min(spcData[0].lslValue, minValue);
        } else {
          let t_v = value.map(tv => tv.value);
          min = Math.min(min, spcData[0].lslValue, ...t_v);
        }
        if (valueIsEmpty(max)) {
          let maxValue = value.reduce((max, obj) => {
            return obj.value > max ? obj.value : max;
          }, 0);
          max = Math.max(spcData[0].uslValue, maxValue);
        } else {
          let t_v = value.map(tv => tv.value);
          max = Math.max(max, spcData[0].uslValue, ...t_v);
        }
        timeList = spcData[0].pointValues.map(v => dayjs(v.time).format("YYYY-MM-DD HH:mm:ss"));
      }
    }
    pointValues.push(value);
  }
  // echarts 热力图
  chartOptions.value = {
    tooltip: {
      position: "top",
      formatter: function (params) {
        return params.name + "<br>" + submainList.value[params.value[1]] + "，value: " + params.value[2];
      }
    },
    grid: {
      height: "80%",
      top: "1%"
    },
    xAxis: {
      type: "category",
      data: timeList,
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: "category",
      data: submainList.value,
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min,
      max,
      calculable: true,
      orient: "horizontal",
      left: "center",
      bottom: "0",
      inRange: {
        color: ["#2059E9", "#FFF9FF", "#CF2140"]
      }
    },
    series: [
      {
        name: seriesName,
        type: "heatmap",
        data: getHotMapData(pointValues, timeList),
        label: {
          show: false
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };
  chartRef.value.updateEchartsOption();
};
const activeTabChange = () => {
  hotActiveName.value = 0;
  getPointList("MIC_SUPPLY_" + activeTab.value);
};
const activeMeasureChange = () => {
  handleQueryP();
};
onMounted(() => {
  getPointList("MIC_SUPPLY_" + activeTab.value);
  getFabList();
  // getPerdictionDict();
});
onUnmounted(() => {
  clearClock();
});
</script>

<style scoped lang="scss">
.supply-mng {
  position: relative;

  .swtich-btn {
    position: absolute;
    top: 20px;
    right: 20px;
  }
}

.moudle-item {
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.box {
  display: flex;
  gap: 16px;
  height: 532px;
  overflow: hidden;

  .box-title {
    position: relative;
    display: flex;
    align-items: center;
    height: 22px;
    padding: 16px 0 16px 12px;
    margin: 16px 0 8px;

    &::before {
      position: absolute;
      left: 0;
      width: 3px;
      height: 22px;
      content: "";
      background: #3b82f6;
    }
  }

  .box-border {
    box-sizing: border-box;
    height: 475px;
    padding: 16px;
    border: 1px solid #dcdcdc;
  }

  .left {
    flex: 1;
    gap: 24px;
    height: 100%;
  }

  .right {
    flex: 1;
    height: 100%;
  }
}

:deep(.px-table) {
  .px-table__cell {
    padding: 6px 0;
  }

  .px-table__header-wrapper,
  .px-table__fixed-header-wrapper {
    th {
      background-color: #e7eefb !important;
    }
  }
}

:deep(.time-type-item) {
  border: none !important;
}

.chartsdom {
  width: 100%;
  height: 405px;
  background: white;

  > div {
    height: 100%;
  }
}

.chart-container {
  width: 100%;
}

.chart-wrapper {
  width: 100%;
}

.warning-icon {
  position: relative;
  top: 2px;
  display: inline-block;
  padding-right: 3px;
}

.warning-text {
  padding-left: 3px;
}

:deep(.px-table .px-table__body) {
  td {
    &.oos {
      background: #feecec !important;

      &:hover {
        background-color: #feecec !important;
      }

      span {
        color: #ef4444;
      }
    }

    &.ooc {
      background: #fef5e6 !important;

      &:hover {
        background-color: #fef5e6 !important;
      }

      span {
        color: #f59e0b;
      }
    }

    &.oow {
      background: #fff1e8 !important;

      &:hover {
        background-color: #fff1e8 !important;
      }

      span {
        color: #f59e0b;
      }
    }
  }
}

:deep(.echarts-chart) {
  height: 405px;
  padding: 0;

  .echarts-chart-com {
    height: 100%;
    margin-top: 12px;
  }
}

:deep(.px-tabs__nav) {
  margin-top: 0;
}
</style>
